package com.A21MobileSales;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ActionMode;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.A21.Adapter.TrnDetailAdapter;
import com.A21.Adapter.TrnDetailAdapter.UpdateQuantityListener;
import com.A21.Object.Global;
import com.A21.Object.TrnDetail;
import com.A21MobileSales.DataBase.DatabaseHelper;

public class OrderDetail extends Activity {

	public static final int PRODUCT_DETAILS_ACTIVITY = 1;
	public static final int GLOBAL_DISCOUNT_ACTIVITY = 2;
	private ListView lsvCart;
	private String CustCode, CName, Id, TrnType, GST, GSTInc;
	public String DiscountType;
	private TextView lblTotal, lblTax, lblSubTotal, lblGST, lblGrandTotal;// lblGlobDiscount,
																			// lblDiscount
	public TrnDetailAdapter cartAdapter;
	private double SubTotal, GSTAmount, GrandTotal, DiscountAmt;
	public double DiscountPer;
	public ArrayList<TrnDetail> list;
	DatabaseHelper objDBHelper;
	DecimalFormat df2 = new DecimalFormat("#0.00");
	public ActionMode mActionMode;
	String CurrentTableDetail;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.order_detail);

		if (getIntent().hasExtra("Code")) {
			CustCode = getIntent().getStringExtra("Code");
		}
		if (getIntent().hasExtra("CName")) {
			CName = getIntent().getStringExtra("CName");
		}
		if (getIntent().hasExtra("Id")) {
			Id = getIntent().getStringExtra("Id");
		}
		if (getIntent().hasExtra("TrnType")) {
			TrnType = getIntent().getStringExtra("TrnType");
		}

		if (getIntent().hasExtra("GST")) {
			GST = getIntent().getStringExtra("GST");
		}
		if (getIntent().hasExtra("GSTInc")) {
			GSTInc = getIntent().getStringExtra("GSTInc");
		}
		if (getIntent().hasExtra("DiscountType")) {
			DiscountType = getIntent().getStringExtra("DiscountType");
		}
		if (getIntent().hasExtra("DiscountPer")) {
			DiscountPer = Double.valueOf(getIntent().getStringExtra(
					"DiscountPer"));
			// DiscountAmt=Global.RD(Double.valueOf(SubTotal)*(DiscountPer), 2);
		}
		if (TrnType.equals("CW")) {
			CurrentTableDetail = "A21OPOrderDetail";
		} else if (TrnType.equals("CA")) {
			CurrentTableDetail = "A21OPCashInvoiceDetail";

		} else if (TrnType.equals("CR")) {
			CurrentTableDetail = "A21OPCreditInvoiceDetail";
		}
		list = new ArrayList<TrnDetail>();
		lsvCart = (ListView) findViewById(R.id.lsvCart);
		lsvCart.setDivider(null);
		lblTotal = (TextView) findViewById(R.id.lblTotal);
		lblTax = (TextView) findViewById(R.id.lblTax);
		lblGST = (TextView) findViewById(R.id.lblGST);
		lblSubTotal = (TextView) findViewById(R.id.lblSTotal);
		// lblDiscount = (TextView) findViewById(R.id.lblDiscount);
		lblGrandTotal = (TextView) findViewById(R.id.lblGrandTotal);
		// lblGlobDiscount = (TextView) findViewById(R.id.lblGlobDiscount);

		if (!Global.getMSTSettings().GlobalDiscount) {
			// lblGlobDiscount.setVisibility(View.GONE);
			// lblDiscount.setVisibility(View.GONE);
		}

		initData();
		// lblGlobDiscount.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// Intent intent = new Intent();
		// intent.setClass(OrderDetail.this, GlobalDiscount.class);
		// Bundle bundle = new Bundle();
		// double value = DiscountAmt;
		// if (DiscountType.equals("P")) {
		// value = DiscountPer;
		// }
		// bundle.putString("SubTotal", String.valueOf(SubTotal));
		// bundle.putString("Value", String.valueOf(value));
		// bundle.putString("DiscountType", String.valueOf(DiscountType));
		// intent.putExtras(bundle);
		// startActivityForResult(intent, 2);
		// }
		// });

		lsvCart.setLongClickable(true);
	}

	public void ClearSelection() {
		for (TrnDetail row : list) {
			row.isTrue = false;
		}
		cartAdapter.notifyDataSetChanged();
	}

	public void DeleteSelection() {
		Iterator<TrnDetail> lst = list.iterator();
		while (lst.hasNext()) {
			TrnDetail row = lst.next();
			if (row.isTrue) {
				if (row.Id > 0) {
					objDBHelper = new DatabaseHelper(this);
					objDBHelper.DeleteRowByTableId(CurrentTableDetail,
							String.valueOf(row.Id));
				}
				lst.remove();
			}
		}
		cartAdapter.notifyDataSetChanged();
		mActionMode.finish();
	}

	public void UpdateList(ArrayList<TrnDetail> val) {
		list = val;
	}

	public void UpdateDetailFromTab(TrnDetail det) {
		if (list == null)
			list = new ArrayList<TrnDetail>();
		int nextId = 0;
		for (TrnDetail row : list) {
			if (det.Id == row.Id) {
				row.Product = det.Product;
				row.HeaderId = det.HeaderId;
				row.ProdDesc = det.ProdDesc;
				row.OrderQuantity = det.OrderQuantity;
				row.Conversion = det.Conversion;
				row.UnitPrice = det.UnitPrice;
				row.LineDiscount1 = det.LineDiscount1;
				row.UOM = det.UOM;
				row.StockUnit = det.StockUnit;
				row.DetailMemo = det.DetailMemo;
				row.ReservedField1 = det.ReservedField1;
				row.ReservedField2 = det.ReservedField2;
				row.ReservedField3 = det.ReservedField3;
				row.ReservedField4 = det.ReservedField4;
				row.ReservedField5 = det.ReservedField5;
				break;
			}
			if (row.Id < nextId)
				nextId = row.Id;
		}
		if (det.Id == 0) {
			det.Id = nextId - 1;
			list.add(det);
		}
		updateTotal();
		cartAdapter = new TrnDetailAdapter(CustCode, OrderDetail.this, list,
				new UpdateQuantityListener() {
					@Override
					public void onUpdate(boolean isPlus, int index) {
						if (isPlus) {
							list.get(index).OrderQuantity = list.get(index).OrderQuantity + 1;
							updateTotal();
							try {
								if (TrnType.equals("CW")) {
									objDBHelper.SaveOrderDetail(
											CurrentTableDetail, list.get(index));
								}
							} catch (Exception ex) {
								Toast.makeText(OrderDetail.this,
										ex.getMessage(), Toast.LENGTH_SHORT)
										.show();
							}
						} else {
							if (list.get(index).OrderQuantity > 0) {
								list.get(index).OrderQuantity = list.get(index).OrderQuantity - 1;
								updateTotal();
								try {
									if (TrnType.equals("CW")) {
										objDBHelper.SaveOrderDetail(
												CurrentTableDetail,
												list.get(index));

									}
								} catch (Exception ex) {
									Toast.makeText(OrderDetail.this,
											ex.getMessage(), Toast.LENGTH_SHORT)
											.show();
								}
							} else {
								try {
									if (TrnType.equals("CW")) {
										objDBHelper.DeleteRowByTableId(
												CurrentTableDetail, String
														.valueOf(list
																.get(index).Id));
									}
								} catch (Exception ex) {
									Toast.makeText(OrderDetail.this,
											ex.getMessage(), Toast.LENGTH_SHORT)
											.show();
								}
							}
						}

						cartAdapter.notifyDataSetChanged();

					}
				});

		lsvCart.setAdapter(cartAdapter);

	}

	private void initData() {
		getListCart();
		updateTotal();
		objDBHelper = new DatabaseHelper(this);
		cartAdapter = new TrnDetailAdapter(CustCode, OrderDetail.this, list,
				new UpdateQuantityListener() {
					@Override
					public void onUpdate(boolean isPlus, int index) {
						if (isPlus) {
							list.get(index).OrderQuantity = list.get(index).OrderQuantity + 1;
							updateTotal();
							try {
								if (TrnType.equals("CW")) {
									objDBHelper.SaveOrderDetail(
											CurrentTableDetail, list.get(index));
								}
							} catch (Exception ex) {
								Toast.makeText(OrderDetail.this,
										ex.getMessage(), Toast.LENGTH_SHORT)
										.show();
							}
						} else {
							if (list.get(index).OrderQuantity > 0) {
								list.get(index).OrderQuantity = list.get(index).OrderQuantity - 1;
								updateTotal();
								try {
									if (TrnType.equals("CW")) {
										objDBHelper.SaveOrderDetail(
												CurrentTableDetail,
												list.get(index));

									}
								} catch (Exception ex) {
									Toast.makeText(OrderDetail.this,
											ex.getMessage(), Toast.LENGTH_SHORT)
											.show();
								}
							} else {
								try {
									objDBHelper.DeleteRowByTableId(
											CurrentTableDetail,
											String.valueOf(list.get(index).Id));
								} catch (Exception ex) {
									Toast.makeText(OrderDetail.this,
											ex.getMessage(), Toast.LENGTH_SHORT)
											.show();
								}
							}
						}

						cartAdapter.notifyDataSetChanged();
					}
				});

		lsvCart.setAdapter(cartAdapter);

	}

	private void updateTotal() {
		// =IIf(GSTInc,'Total Less GST','Total with GST')
		GrandTotal = 0;
		SubTotal = 0;
		String strTotalLable = "";
		for (TrnDetail element : list) {
			SubTotal += element.OrderQuantity
					* (element.UnitPrice - (element.UnitPrice * element.LineDiscount1));
		}
		boolean GstInclusive = GSTInc == "1" ? true : false;

		/*
		 * if (DiscountType.equals("A") && DiscountAmt != 0) { DiscountPer =
		 * DiscountAmt / SubTotal; } else {
		 * 
		 * }
		 */
		DiscountAmt = Global.RD(Double.valueOf(SubTotal) * (DiscountPer), 2);
		double gstRate = Double.valueOf(GST);
		if (GstInclusive) {
			strTotalLable = "TOTAL LESS GST";
			GSTAmount = Global.RD((SubTotal - DiscountAmt)
					* (1 - (1 / (1 + gstRate))), 2);
			GrandTotal = SubTotal - DiscountAmt - GSTAmount;
		} else {
			strTotalLable = "TOTAL WITH GST";
			GSTAmount = (SubTotal - DiscountAmt) * gstRate;
			GrandTotal = SubTotal - DiscountAmt + GSTAmount;
		}
		lblSubTotal.setText(df2.format(SubTotal) + "");
		lblTotal.setText(df2.format(GrandTotal) + "");
		lblGST.setText((getString(R.string.GST) + " "
				+ df2.format(gstRate * 100) + "%").toUpperCase());
		lblTax.setText(df2.format(GSTAmount) + "");
		// lblDiscount.setText(df2.format(DiscountAmt) + "");
		lblGrandTotal.setText(strTotalLable);
		// lblGlobDiscount.setText("Global Discount"
		// + (DiscountType.equals("P") ? " (" + Global.RD(DiscountPer, 2)
		// * 100 + "%) : " : " : "));
	}

	private void getListCart() {
		objDBHelper = new DatabaseHelper(this);
		list = objDBHelper.GetOrderDetailByHeaderId(CurrentTableDetail, Id);
	}

	@Override
	public void onBackPressed() {
		OrderTab parent = (OrderTab) getParent();
		parent.getTabHost().setCurrentTab(parent.previous_tab);
	}

	@SuppressLint("NewApi")
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case PRODUCT_DETAILS_ACTIVITY:
			if (resultCode == RESULT_OK) {
				Bundle bundle = data.getExtras();
				String status = bundle.getString("status");
				if (status.equalsIgnoreCase("done")) {
					if (Global.getSelectedTrnDetail() != null) {
						UpdateDetailFromTab(Global.getSelectedTrnDetail());
						Global.setSelectedTrnDetail(null);
					}

				}
			} else if (resultCode == RESULT_CANCELED) {

			}
			break;
		case GLOBAL_DISCOUNT_ACTIVITY:
			if (resultCode == RESULT_OK) {
				Bundle bundle = data.getExtras();
				String status = bundle.getString("status");
				if (status.equalsIgnoreCase("done")) {
					String Amt = bundle.getString("Amt");
					String Per = bundle.getString("Per");
					String DType = bundle.getString("Type");
					DiscountAmt = Double.valueOf(Amt);
					DiscountPer = Double.valueOf(Per);
					DiscountType = DType;

					if (DiscountType.equals("A")) {
						DiscountPer = DiscountAmt / SubTotal;
					} else {
						DiscountAmt = Global.RD(Double.valueOf(SubTotal)
								* (DiscountPer), 2);
					}
					updateTotal();
				}
			} else if (resultCode == RESULT_CANCELED) {

			}
			break;
		}

	}

}
